import {message} from "antd";
import dayjs from 'dayjs';
import {request} from 'umi';

export const uploadAliyunOSS = params => {
  const formData = new FormData();
  formData.append('file', params.file);

  request('/aliyun-oss/upload', {
    method: 'POST',
    headers: {'Content-Type': 'multipart/form-data'},
    data: formData,
  }).then(rest => {
    if (rest.code === 0) {
      if (params.file.type.startsWith('image')) {
        params.success({type: 'IMAGE', url: rest.data.url});
      }
      if (params.file.type.startsWith('video')) {
        params.success({type: 'VIDEO', url: rest.data.url});
      }
    } else {
      params.error({msg: '上传失败'});
    }
  });
}

export const uploadFn = params => {
  const formData = new FormData();
  formData.append('file', params.file);

  request('/minio/upload', {
    method: 'POST',
    headers: {'Content-Type': 'multipart/form-data'},
    data: formData,
  }).then(rest => {
    if (rest.code === 0) {
      if (params.file.type.startsWith('image')) {
        params.success({type: 'IMAGE', url: rest.data.url});
      }
      if (params.file.type.startsWith('video')) {
        params.success({type: 'VIDEO', url: rest.data.url});
      }
    } else {
      params.error({msg: '上传失败'});
    }
  });
}

export const uuid = () => {
  if (typeof crypto === 'object') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID();
    }
    if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
      const callback = (c) => {
        const num = Number(c);
        return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16);
      };
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, callback);
    }
  }
  let timestamp = new Date().getTime();
  let perforNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let random = Math.random() * 16;
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0;
      timestamp = Math.floor(timestamp / 16);
    } else {
      random = (perforNow + random) % 16 | 0;
      perforNow = Math.floor(perforNow / 16);
    }
    return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
  });
};

export const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};

export const normFile = (e) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

export const beforeUpload = (file, size) => {
  const isLt = file.size / 1024 / 1024 < size;
  if (!isLt) {
    message.error(`文件必须小于 ${size}MB！`).then();
  }
  return isLt;
};

export const dataURLtoBlob = function (dataurl) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type: mime});
};

export const genKey = (prefix, fileName) => {
  let newFileName = uuid() + "." + fileName.split(".").pop();
  let date = dayjs(new Date()).format("YYYYMMDD");
  return `${prefix}/${date}/${newFileName}`;
};